package com.appointment.interceptor;

import com.appointment.utils.Jwt.JwtUtil;
import com.appointment.annotation.RoleRequired;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    private static final String OPTIONS = "OPTIONS";

    private static final String BEARER_PREFIX = "Bearer ";

    private static final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行OPTIONS请求
        // 为了解决跨域问题，浏览器会先发送一个OPTIONS请求，如果不放行，后续请求会被拦截
        if (OPTIONS.equals(request.getMethod())) {
            return true;
        }

        // 获取token
        String token = request.getHeader(AUTHORIZATION_HEADER);
        if (token != null && token.startsWith(BEARER_PREFIX)) {
            token = token.substring(BEARER_PREFIX.length());
            // 验证token
            if (jwtUtil.validateToken(token) && !jwtUtil.isBlackList(token)) {
                String id = jwtUtil.getIdFromToken(token);
                String role = jwtUtil.getRoleFromToken(token);
                // 将用户信息存入request
                request.setAttribute("token", token);
                request.setAttribute("id", id);
                request.setAttribute("role", role);

                if (handler instanceof HandlerMethod) {
                    Method method = ((HandlerMethod) handler).getMethod();
                    RoleRequired roleRequired = method.getAnnotation(RoleRequired.class);
                    if (roleRequired != null) {
                        List<String> roles = Arrays.asList(roleRequired.value());
                        // 判断用户角色是否符合要求
                        if (!roles.contains(role)) {
                            return unauthorizedAccess(response, request.getRequestURI());
                        }

                    }
                    return true;
                }
            }
            return unauthorizedAccess(response, request.getRequestURI());
        }
        return unauthorizedAccess(response, request.getRequestURI());
    }

    private boolean unauthorizedAccess(HttpServletResponse response, String requestURI) {
        // 记录未授权访问
        log.warn("Unauthorized access attempt to: {}", requestURI);
        // 设置 401 状态码
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}